﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CuaHangMayTinh.BusinessEntities;
using CuaHangMayTinh.DataProvider;
using CuaHangMayTinh.Utilities;
using System.Data;


namespace CuaHangMayTinh.DataAccessLayer
{
    public class BanHangDA
    {
        public BanHangDA()
        {
        }

        /// <summary>
        /// Hàm thêm 1 hóa đơn bán hàng mới
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Insert(BanHangEntity entity)
        {
            try
            {
                ParameterBuilder pb = DBFactory.CreateParamBuilder();

                pb.AddParameter("MaNV", entity.MaNV);
                pb.AddParameter("MaKH", entity.MaKH);
                pb.AddParameter("NgayLap", entity.NgayLap);
                pb.AddParameter("VAT", entity.VAT);
                pb.AddParameter("LoiNhuan", entity.LoiNhuan);
                pb.AddParameter("TongTien", entity.TongTien);
                pb.AddParameter("GhiChu", entity.GhiChu);
                return (int)DBFactory.Database.ExecuteNonQuery("BanHang_Insert", pb.Parameters);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return 0;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        int InsertTS(BanHangEntity entity, DbConnector conn, System.Data.Common.DbTransaction tran)
        {
            try
            {
                ParameterBuilder pb = DBFactory.CreateParamBuilder();

                pb.AddParameter("MaNV", entity.MaNV);
                pb.AddParameter("MaKH", entity.MaKH);
                pb.AddParameter("NgayLap", entity.NgayLap);
                pb.AddParameter("VAT", entity.VAT);
                pb.AddParameter("LoiNhuan", entity.LoiNhuan);
                pb.AddParameter("TongTien", entity.TongTien);
                pb.AddParameter("GhiChu", entity.GhiChu);
                return (int)DBFactory.Database.ExecuteNonQueryGetID("BanHang_Insert", pb.Parameters, conn, tran);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return 0;
            }
        }

        /// <summary>
        /// Hàm thêm 1 thông tin bán hàng vào các bảng BanHang, ChiTietBan, ModelMatHang, MatHang trên CSDL, sử dụng với transaction
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int InsertTS(BanHangEntity entity)
        {
            try
            {
                DbConnector conn = DBFactory.Database.GetConnector();
                System.Data.Common.DbTransaction tran = DBFactory.Database.CreateTransaction(conn);

                int IDBH = this.InsertTS(entity, conn, tran);
                if (IDBH == 0)
                    return 0;

                int countModel = entity.ListModel.Count;

                for (int i = 0; i < countModel; i++)
                {
                    //
                    ModelMatHangEntity model = entity.ListModel[i];
                    int IDModel = model.MaModelMH;
                    //
                    ChiTietBanHangEntity chitiet = entity.ListChiTiet[i];
                    chitiet.MaHDBan = IDBH;
                    chitiet.MaModelMH = IDModel;
                    if (ChiTietBanHangDA.Insert(chitiet, conn, tran) == 0)
                        return 0;

                    int countmathang = model.ListMatHang.Count;
                    for (int j = 0; j < countmathang; j++)
                    {
                        MatHangEntity mathang = model.ListMatHang[j];
                        mathang.MaHoaDonBan = IDBH;
                        mathang.TinhTrang = 1;
                        if (!MatHangDA.UpDateDaBanTS(mathang, conn, tran))
                            return 0;
                    }
                }
                DBFactory.Database.CommitTransaction(conn, tran);
                return IDBH;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return 0;
            }
        }

        /// <summary>
        /// Hàm Cập nhật thông tin của 1 hóa đơn
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpDate(BanHangEntity entity)
        {
            try
            {
                ParameterBuilder pb = DBFactory.CreateParamBuilder();
                pb.AddParameter("MaBanHang", entity.MaBanHang);
                pb.AddParameter("MaHoaDonBH", entity.MaHoaDonBH);
                pb.AddParameter("MaNV", entity.MaNV);
                pb.AddParameter("MaKH", entity.MaKH);
                pb.AddParameter("NgayLapHoaDon", entity.NgayLap);
                pb.AddParameter("LoiNhuan", entity.LoiNhuan);
                pb.AddParameter("TongTien", entity.TongTien);
                pb.AddParameter("GhiChu", entity.GhiChu);
                int numRowEffected = DBFactory.Database.ExecuteNonQuery("BanHang_UpDate", pb.Parameters);
                return (numRowEffected > 0);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return false;
            }
        }

        /// <summary>
        /// Hàm lấy tất cả thông tin của hóa đơn bán hàng
        /// </summary>
        /// <param name="View"></param>
        /// <returns></returns>
        public DataTable Find_All(bool View)
        {
            try
            {
                DataTable dt = new DataTable();
                ParameterBuilder pb = DBFactory.CreateParamBuilder();
                pb.AddParameter("View", View);

                dt = DBFactory.Database.FillDataTable("BanHang_FindAll", pb.Parameters);
                return dt;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                throw new Exception(ex.Message, ex);
            }
        }

        /// <summary>
        /// Hàm tìm thông tin của nhân viên bằng ID của hóa đơn
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataTable Find_ID(int id)
        {
            try
            {
                DataTable dt = new DataTable();
                ParameterBuilder pd = DBFactory.CreateParamBuilder();
                pd.AddParameter("ID", id);

                dt = DBFactory.Database.FillDataTable("BanHang_Find_ID", pd.Parameters);
                return dt;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return null;
            }
        }

        /// <summary>
        /// Hàm Lấy thông tin của mã hóa đơn có mã số là mới nhất
        /// </summary>
        /// <returns></returns>
        public DataTable GetMaHDMax()
        {
            try
            {
                DataTable dt = new DataTable();
                ParameterBuilder pd = DBFactory.CreateParamBuilder();

                dt = DBFactory.Database.FillDataTable("BanHang_GetMaHDMax", pd.Parameters);
                return dt;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return null;
            }
        }

        /// <summary>
        /// Hàm Lấy thông tin bán hàng từ Mã bán hàng
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        DataTable GetInfoBanHang_ID(int id)
        {
            try
            {
                DataTable dt = new DataTable();
                ParameterBuilder pd = DBFactory.CreateParamBuilder();
                pd.AddParameter("MaBanHang", id);

                dt = DBFactory.Database.FillDataTable("BanHang_Find_MaBanHang", pd.Parameters);
                return dt;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return null;
            }
        }

        /// <summary>
        /// Hàm get toàn bộ thông của bán hàng, listmodel, list chi tiết bán, list mặt hàng bán
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BanHangEntity GetAllInfo_ID(int id)
        {
            try
            {
                List<BanHangEntity> banhangs = ConvertToList(this.GetInfoBanHang_ID(id));

                BanHangEntity banhang = banhangs[0];

                ChiTietBanHangDA chitietda = new ChiTietBanHangDA();

                List<ChiTietBanHangEntity> chitiets = chitietda.ConvertToList(chitietda.GetInfo_ByMaBanHang(id));

                ModelMatHangDA modelda = new ModelMatHangDA();

                List<ModelMatHangEntity> models = new List<ModelMatHangEntity>();

                MatHangDA mathangda = new MatHangDA();

                foreach (var chitiet in chitiets)
                {
                    ModelMatHangEntity model = modelda.ConvertToList(modelda.Find_ID(chitiet.MaModelMH, false))[0];
                    models.Add(model);
                }

                foreach (var model in models)
                {
                    List<MatHangEntity> mathangs = new List<MatHangEntity>();
                    DataTable dt = mathangda.Find_MaModelMH_MaBanHang(model.MaModelMH, id, false);
                    mathangs = mathangda.ConvertToList(mathangda.Find_MaModelMH_MaBanHang(model.MaModelMH, id, false));
                    model.ListMatHang = mathangs;
                }

                banhang.ListChiTiet = chitiets;

                banhang.ListModel = models;

                return banhang;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public DataTable GetInfoHoaDon()
        {
            try
            {
                DataTable dt = new DataTable();
                ParameterBuilder pd = DBFactory.CreateParamBuilder();

                dt = DBFactory.Database.FillDataTable("BanHang_GetInfoHoaDon", pd.Parameters);
                return dt;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public DataTable ThongKe_BanHangModel()
        {
            try
            {
                DataTable dt = new DataTable();
                ParameterBuilder pd = DBFactory.CreateParamBuilder();

                dt = DBFactory.Database.FillDataTable("ThongKe_BanHang", pd.Parameters);
                return dt;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public List<BanHangEntity> ConvertToList(DataTable dt)
        {
            List<BanHangEntity> list = new List<BanHangEntity>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int ma = (int)dt.Rows[i][0];
                string mahd = dt.Rows[i][1].ToString();
                int manv = (int)dt.Rows[i][2];
                int makh = (int)dt.Rows[i][3];
                DateTime ngaylap = (DateTime)dt.Rows[i][4];
                float vat = float.Parse(dt.Rows[i][5].ToString());
                float loinhuan = float.Parse(dt.Rows[i][6].ToString());
                decimal tong = decimal.Parse(dt.Rows[i][7].ToString());
                string ghichu = dt.Rows[i][8].ToString();

                BanHangEntity a = new BanHangEntity(ma, mahd, manv, makh, ngaylap, vat, loinhuan, tong, ghichu);
                list.Add(a);
            }
            return list;
        }
    }
}
